package dtaskboard.client.project.dialog;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import dtaskboard.client.Constants;
import dtaskboard.client.DialogUtil;
import dtaskboard.client.project.ProjectPage;
import dtaskboard.client.service.ProjectService;
import dtaskboard.client.service.ProjectServiceAsync;

public class CreateHistoryDialog extends DialogBox {

  private final TextBox name;


  public CreateHistoryDialog(String projectName) {
    this.name = new TextBox();

    Label nameLabel = new Label("Nome da história");

    Panel panel = new VerticalPanel();

    panel.add(nameLabel);
    panel.add(this.name);
    panel.add(new CreateHistorySubmitButton(projectName));


    super.setAnimationEnabled(true);
    super.setAutoHideEnabled(true);
    super.setHTML("Criação de história");
    super.setGlassEnabled(true);
    super.setModal(true);
    super.setWidget(panel);
    super.setVisible(true);
  }

  class CreateHistorySubmitButton extends Button {
    public CreateHistorySubmitButton(final String projectName) {
      this.setText("Criar história");
      this.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          ProjectServiceAsync projectService = GWT.create(ProjectService.class);
          final CreateHistoryDialog chd = CreateHistoryDialog.this;
          String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
          projectService.createHistory(projectName, chd.name.getText(),
              sessionId, new AsyncCallback<Void>() {

                @Override
                public void onFailure(Throwable caught) {
                  DialogUtil.closableDialog("Criação de história",
                      "Ocorreu um erro ao salvar a história.");
                }

                @Override
                public void onSuccess(Void result) {
                  // DialogUtil.closableDialog("Criação de história",
                  // "História salva com sucesso.");
                  chd.hide();
                  new ProjectPage(projectName);
                }
              });
        }
      });
    }
  }

}
